Dynamic parameters in Svelte actions

Posted on 2023-04-02 by

henrikvilhelmberglund

As we said before, Svelte actions are run when the component is initialized (mounted to the DOM). How do we make a dynamic parameter then? How do we make the action do something when the variable changes?

Here our div using an action doesn't update when we change the name.
name: world
<script>
	let name = "world";

	function lihauAction(node, params) {
		console.log(node, params);
		node.innerHTML = params;
		return {
			destroy() {
				console.log("node was destroyed");
			},
		};
	}
</script>

<input bind:value={name} />

<div use:lihauAction={name} />

name: {name}

<style>
</style>

Luckily for us you can have another function in the action return statement called update() . It will run every time the params change. Let's try it!

If we add an update() function in the return statement we can do something when the params change.
name: world
<script>
	let name = "world";

	function lihauAction(node, params) {
		console.log(node, params);
		node.innerHTML = params;
		return {
			update(newParams) {
				console.log("updated!", newParams);
				node.innerHTML = newParams;
			},
			destroy() {
				console.log("node was destroyed");
			},
		};
	}
</script>

<input bind:value={name} />

<div use:lihauAction={name} />

name: {name}

<style>
</style>